package cn.zlp.hrm.handler;

import cn.zlp.hrm.config.RabbitMQConfig;
import cn.zlp.hrm.domain.Order;
import cn.zlp.hrm.mapper.OrderMapper;
import cn.zlp.hrm.vo.OrderCancelVo2Queue;
import com.rabbitmq.client.Channel;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

//预创订单取消Handler
@Component
public class OrderCancelHandler {


    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private OrderMapper orderMapper;

    @RabbitListener(queues = RabbitMQConfig.DELAY_QUEUE_ORDER)
    public void handle(OrderCancelVo2Queue vo, Message message, Channel channel){

        Long orderId = vo.getOrderId();
        Long killCourId = vo.getKillCourseId();
        String paySn = vo.getPaySn();
        //1 修改订单库状态
        Order order = orderMapper.selectById(orderId);
        order.setStatusPay("-1");
        order.setStatusOrder(-1);
        orderMapper.updateById(order);

        //2 修改支付单状态 @TODO 支付单SN

        //3 退库存
        RSemaphore semaphore = redissonClient
                .getSemaphore("kill_course_" +killCourId);
        semaphore.release(1);

        //4 手动签收
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}